const { body } = require('express-validator')
const validate = require('../middleware/validate')
const { User } = require('../model')
const md5 = require('../util/md5')

exports.login = [
  validate([
    body('user.email')
      .notEmpty().withMessage('邮箱不能为空')
      .isEmail().withMessage('邮箱格式不正确'),
    body('user.password')
      .notEmpty().withMessage('密码不能为空')
  ]),
  validate([
    // 查询数据库，用户是否存在
    body('user.email').custom(async (email, { req }) => {
      const user = await User.findOne({ email }).select(['username', 'password', 'email', 'bio', 'image'])
      if (!user) {
        return Promise.reject('用户不存在')
      }
      req.user = user
    })
  ]),
  validate([
    // 校验密码是否正确
    body('user.password').custom(async (password, { req }) => {
      console.log(req.user)
      if (md5(password) !== req.user.password) {
        return Promise.reject('密码错误')
      }
    })
  ])
]

exports.register = validate([
  body('user.username')
    .notEmpty().withMessage('用户名不能为空')
    .bail()
    .isLength({ min: 2, max: 10 }).withMessage('用户名最少2位'),
  body('user.email')
    .notEmpty().withMessage('email 不能为空')
    .bail()
    .isEmail().withMessage('邮箱格式不正确')
    .bail()
    .custom(async email => {
      const user = await User.findOne({ email })
      if (user) {
        return Promise.reject('邮箱已存在')
      }
    }),
  body('user.password')
    .notEmpty().withMessage('密码不能为空')
    .bail()
    .isLength({ min: 6, max: 10 }).withMessage('密码最少6位，最多10位')
])